package com.igeek.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.igeek.boot.entity.Menu;
import com.igeek.boot.mapper.MenuMapper;
import com.igeek.boot.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.boot.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jwj
 * @since 2023-12-27
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    //查询所有菜单信息
    //添加缓存信息至Redis中
    @Cacheable(cacheNames = "menu",keyGenerator = "keyGenerator")
    @Transactional(readOnly = true)
    @Override
    public List<MenuVO> finAll(Integer userId) {
        //1.查询level等级为1的path路径
        List<Menu> menusByLevel=menuMapper.selectMenuByUserId(userId,1);

        //2，封装所有菜单信息
        List<MenuVO> menus = new ArrayList<>();
        menusByLevel.forEach(menu -> {
            List<Map<String, String>> mapList = menuMapper.findMap(userId,menu.getPath());
            MenuVO first = new MenuVO();
            List<MenuVO> child = new ArrayList<>();
            mapList.forEach(map -> {
                //封装第一级目录
                first.setPath(map.get("path1"));
                first.setTitle(map.get("name1"));
                first.setIcon(map.get("icon1"));

                //封装第二级目录
                MenuVO second = new MenuVO();
                second.setPath(map.get("path2"));
                second.setTitle(map.get("name2"));
                second.setLinkUrl(map.get("link_url"));
                second.setIcon(map.get("icon2"));
                child.add(second);
            });
            first.setChildren(child);
            menus.add(first);
        });
        return menus;
    }
}
